<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">&emsp;新增&emsp;</el-button>
          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>

          <el-form :inline="true" :model="listQuery" ref="listQuery" class="demo-form-inline">
            <el-form-item prop="add_time">
              <el-date-picker v-model="listQuery.add_time" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择添加时间"></el-date-picker>
            </el-form-item>
            <el-form-item prop="good_number">
              <el-input type="text" v-model="listQuery.good_number" placeholder="请输入靓号"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchSubmit">查询</el-button>
              <el-button type="primary" @click="resetSubmit">重置</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <div class="item">
        <el-table ref="dataList" :data="menuList" @selection-change="handleSelectionChange" style="margin-bottom: 20px;"
                  row-key="id" border :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="序号"></el-table-column>
          <el-table-column prop="good_number" label="靓号编号"></el-table-column>
          <el-table-column prop="user_code" label="原始编号"></el-table-column>
          <el-table-column prop="status" label="使用状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">使用中</el-tag>
              <el-tag v-if="scope.row.status === 0" type="warning">未发放</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="cate_name" label="获取方式"></el-table-column>
          <!-- <el-table-column prop="rebate" label="发放途径" > </el-table-column> -->
          <el-table-column prop="nickname" label="用户昵称"></el-table-column>
          <el-table-column prop="expired_time" label="使用截止时间">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.expired_time === 0" type="success">永久</el-tag>
              <p v-else>{{ scope.row.expired_time }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="add_time" label="添加时间"></el-table-column>
          <!-- <el-table-column prop="" label="操作人" > </el-table-column> -->
          <el-table-column prop="remark" label="备注"></el-table-column>

          <el-table-column min-width="180" label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>编辑
              </el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)" plain>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.perPage"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      title="确定删除吗?"
      :visible.sync="deleteDialogVisible"
      width="435px"
    >
      <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <span slot="footer" class="dialog-footer">
                <el-button @click="deleteDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmDelete">确 定</el-button>
            </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose('dynamicValidateForm')">
      <el-form :model="dynamicValidateForm" :rules="dynamicValidateRules" ref="dynamicValidateForm" label-width="120px">
        <el-form-item label="靓号" prop="good_number">
          <el-input v-model.number="dynamicValidateForm.good_number" placeholder="请输入靓号" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'update'" label="发放用户编号" prop="user_code">
          <el-input v-model.number="dynamicValidateForm.user_code" placeholder="请输入发放用户编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="过期时间" prop="expired_time">
          <el-date-picker v-model="dynamicValidateForm.expired_time" clearable type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择过期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="获取类型" prop="cate_id">
          <el-select filterable v-model="dynamicValidateForm.cate_id" clearable placeholder="请选择类型">
            <el-option
              v-for="item in groupOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dynamicValidateForm.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmSubmit('dynamicValidateForm')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
//   getConfigTypeList,
  listData,
  postCreate,
  putEdit,
  deleteList,
  getCateList
} from '@/api/goodNumber/goodNumberList'

export default {
  data() {
    return {
      // 要修改的当前行的id
      row_id: 0,
      user_code: 0,
      dynamicValidateRules: {
        good_number: [
          {type: 'number', required: true, message: '请填写靓号', trigger: 'blur'},
          //   {  min: 6, max: 6, message: '长度为6位', trigger: 'blur' }
        ],
        cate_id: [{type: 'number', required: true, message: '请选择靓号分类', trigger: 'change'}],
        expired_time: [{required: false, message: '请选择过期时间', trigger: 'change'}],
        remark: [{required: false, message: '请输入备注', trigger: 'blur'}],
        user_code: [{required: true, message: '请输入发放用户编号', trigger: 'blur'}],
      },
      dynamicValidateForm: {
        good_number: undefined,
        cate_id: undefined,
        expired_time: undefined,
        remark: undefined,
        user_code: undefined,
      },
      timestamp: 0,
      dialogFormVisible: false,
      deleteDialogVisible: false,
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '添加'
      },
      listLoading: false,
      total: 0,
      menuList: [],
      listQuery: {
        page: 1,
        perPage: 10,
        add_time: undefined,
        good_number: undefined
      },
      typeOptions: [],
      groupOptions: [],
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: '',

    }
  },
  created() {
    this.getGroupList()
    this.getList()
  },
  methods: {
    // 获取参数配置类型
    getGroupList() {
      getCateList().then(response => {
        response.data.list.forEach(item => {
          let obj = {}
          for (let key in item) {
            if (key === 'id') {
              obj['value'] = item[key]
            } else if (key === 'name') {
              obj['label'] = item[key]
            }
          }
          this.groupOptions.push(obj)
        })
      })
    },
    getList() {
      this.listLoading = true;
      let urlData = "?";
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`;
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`;
      }
      if (this.listQuery.add_time) {
        urlData = urlData + `&add_time=${this.listQuery.add_time}`;
      }
      if (this.listQuery.good_number) {
        urlData = urlData + `&good_number=${this.listQuery.good_number}`;
      }
      // 发送异步请求
      // this.listLoading = false
      listData(urlData).then(({data}) => {
        this.menuList = data.list;
        this.total = data.meta.total
        this.listLoading = false
      })
    },
    // 点击查询
    searchSubmit() {
      this.listQuery.page = 1
      this.getList()
    },
    // 点击重置
    resetSubmit() {
      this.listQuery.page = 1
      this.listQuery.perPage = 10
      this.$refs['listQuery'].resetFields()
    },
    // 点击新增
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {

      this.row_id = row.id
      this.user_code = row.user_code
      this.dynamicValidateForm.good_number = row.good_number
      this.dynamicValidateForm.cate_id = row.cate_id
      if (row.expired_time !== 0) {
        this.dynamicValidateForm.expired_time = row.expired_time
      } else {
        this.dynamicValidateForm.expired_time = undefined
      }
      this.dynamicValidateForm.remark = row.remark
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    // 重置表单内容
    resetForm() {

      this.dynamicValidateForm = {
        good_number: undefined,
        cate_id: undefined,
        expired_time: undefined,
        remark: undefined
      }
      if (this.$refs['dynamicValidateForm']) {
        this.$refs['dynamicValidateForm'].clearValidate() // 清除整个表单的校验
      }
    },
    confirmSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogStatus === 'create') {
            // this.dynamicValidateForm)

            if (this.dynamicValidateForm.expired_time !== null && this.dynamicValidateForm.expired_time !== undefined) {
              let t = new Date(this.dynamicValidateForm.expired_time).getTime().toString();
              t = parseInt(t.substring(0, t.length - 3));
              this.timestamp = t
            } else {
              this.timestamp = 0
            }
            let obj = {};
            for (let key in this.dynamicValidateForm) {
              if (this.dynamicValidateForm[key] !== undefined) {
                obj[key] = this.dynamicValidateForm[key]
              }
            }
            obj.expired_time = this.timestamp;
            postCreate(obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false;
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                });
              } else {
              }
            })
          } else {
            let obj = JSON.parse(JSON.stringify(this.dynamicValidateForm))
            if (obj.expired_time === null) {
              obj.expired_time = 0
            } else {
              let t = new Date(obj.expired_time).getTime().toString();
              t = parseInt(t.substring(0, t.length - 3));
              obj.expired_time = t
            }
            obj.id = this.row_id

            putEdit(obj).then(response => {

              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false;
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                });
              } else {
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = {ids: `${row.id}`}
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选要删除的内容',
          type: 'warning'
        });
        return;
      } else if (this.multipleSelection.length !== 0) {
        let ids = '';
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = {ids: ids}
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {

      // this.dataIds)
      this.deleteDialogVisible = false;
      deleteList(this.dataIds).then((response) => {

        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false;
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          });
        }
      })
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate(); // 清除整个表单的校验
      }
    },
  }
}
</script>

<style scoped>
[v-cloak] {
  display: none;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
}

.demo-form-inline {
  float: right;
}

/deep/ .el-card__header {
  padding-bottom: 0;
}
</style>
